package com.g4.shoppingback.controller;

import com.g4.shoppingback.annotation.WriteLog;
import com.g4.shoppingback.common.Result;
import com.g4.shoppingback.pojo.DdUsersInfo;
import com.g4.shoppingback.service.IDdUsersInfoService;
import com.g4.shoppingback.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/shoppingback/logininfo")
public class UserLoginController implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private IDdUsersInfoService iDdUsersInfoService;
    @Autowired
    private IRoleService iRoleService;

    /**
     * 封装认证信息返回UserDetails对象
     * @param username
     * @return 返回UserDetails
     * @throws UsernameNotFoundException 找不到用户名异常
     */
    @Override
    public UserDetails loadUserByUsername(String username)  {
        DdUsersInfo user = iDdUsersInfoService.selectUser(username);
        //1.判断用户是否存在
        if(user==null) throw new UsernameNotFoundException("该用户不存在!");
        //2.封装用户名,密码,权限返回
        List<String> permissions = iDdUsersInfoService.selectPermissions(user.getId());
        return new User(username, user.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }

    /**
     * 获取用户名和角色
     * @return 返回用户名和角色
     */
    @GetMapping
    public Result getLoginInfo() {
        String username = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String[] loginInfo = new String[]{username,null};
        loginInfo[1]=iRoleService.selectRoleByName(username);
        return Result.ok(loginInfo);
    }

    /**
     * 修改密码
     * @param usedPassword 原密码
     * @param newPassword  新密码
     * @return 返回提示
     */
    @WriteLog("修改密码")
    @PreAuthorize("hasAnyAuthority('miShop:login:updatePassword')")
    @PutMapping("/{usedPassword}/{newPassword}")
    public Result updatePassword(@PathVariable String usedPassword,
                                 @PathVariable String newPassword){
        String username = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        DdUsersInfo ddUsersInfo = iDdUsersInfoService.selectUser(username);
        //必须使用bCryptPasswordEncoder提供的校验方式
        if (!bCryptPasswordEncoder.matches(usedPassword, ddUsersInfo.getPassword())) {
            return Result.error("原密码输入错误!");
        }
        String encodeNewPassword = bCryptPasswordEncoder.encode(newPassword);
        int row = iDdUsersInfoService.updatePassword(ddUsersInfo.getId(),encodeNewPassword);
        if (row==1)return Result.success("密码修改成功");
        return Result.error("密码修改失败");
    }
}
